package com.jy.rhin.config;

import com.alibaba.nacos.spring.context.annotation.config.NacosRefresh;
import com.jy.api.patient.PatientAPI;
import com.jy.api.patient.PatientAPIv1Impl;
import com.jy.api.okhttp.QyjkHealthdcClient;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @ename wade.nie
 * @cname 聂敏
 * @email 550552699@qq.com
 * @date 2024/7/16
 */
@Slf4j
@Getter
@Setter
@Component
@NacosRefresh
@Configuration
@ConfigurationProperties(prefix = "com.cowinhealth")
public class QyjkConfig {

    /**
     * httpclient 超时时间
     */
    private Integer timeout = 120;

    private String version = "v2.0";


    @Bean
    public ConnectionPool okHttpPool() {
        return new ConnectionPool(200, 10, TimeUnit.MINUTES);
    }

    @Bean
    public OkHttpClient okHttpClient(ConnectionPool okHttpPool) {
        Integer timeout = this.getTimeout();
        return new OkHttpClient.Builder().connectionPool(okHttpPool)
                // .retryOnConnectionFailure(false)
                .connectTimeout(timeout, TimeUnit.SECONDS).readTimeout(timeout, TimeUnit.SECONDS).writeTimeout(timeout, TimeUnit.SECONDS)
                .build();
    }

    @Bean("okHttpTemplate")
    public RestTemplate okHttpTemplate(OkHttpClient okHttpClient) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(new OkHttp3ClientHttpRequestFactory(okHttpClient));

        restTemplate.getMessageConverters().forEach(e -> {
            if (e instanceof StringHttpMessageConverter) {
                StringHttpMessageConverter ee = (StringHttpMessageConverter)e;
                ee.setDefaultCharset(StandardCharsets.UTF_8);
            }
        });

        return restTemplate;
    }
}
